package com.imay.live.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Process;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.imay.base.util.StringUtil;
import com.imay.live.R;
import com.imay.live.helper.PreferenceHelper;
import com.mcxiaoke.packer.helper.PackerNg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

public class AppUtil {
    //多进程时,判断是否主进程
    public static boolean isMainProcess(Context context) {
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = context.getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public static String generateDeviceId(Context context) {
        String deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (deviceId == null || "9774d56d682e549c".equals(deviceId)) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if(telephonyManager != null){
                    deviceId = telephonyManager.getDeviceId();
                }
            }
        }
        if (deviceId == null) {
            deviceId = Build.BOARD + Build.BRAND + Build.CPU_ABI + Build.DEVICE + Build.DISPLAY
                    + Build.FINGERPRINT + Build.HOST + Build.ID + Build.MANUFACTURER + Build.MODEL
                    + Build.PRODUCT + Build.TAGS + Build.TYPE + Build.USER + Build.SERIAL;
        }
        return UUID.nameUUIDFromBytes(deviceId.getBytes()).toString();
    }

    public static void startInstalledAppDetailsActivity(final Activity context) {
        if (context == null) {
            return;
        }
        final Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取mac地址
     *
     * @param context
     * @return
     */
    public static String getLocalMacAddress(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(
                Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 获取本地IP
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                if (intf == null) {
                    return "";
                }
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获取运营商
     *
     * @return
     */
    public static String getIsp(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telManager == null) {
                return "";
            }
            String operator = telManager.getSimOperator();
            String isp = "";
            if (operator != null) {
                if (operator.equals("46000") || operator.equals("46002") || operator.equals("46007")) {
                    //中国移动
                    isp = "China Mobile";
                } else if (operator.equals("46001")) {
                    //中国联通
                    isp = "China unicom";
                } else if (operator.equals("46003")) {
                    //中国电信
                    isp = "China Telecom";
                }
            }
            return isp;
        }
        return "";
    }

    /**
     * 俩点经纬度距离计算
     */
    private static final double EARTH_RADIUS = 6378137.0;

    public static double gps2m(double lat_a, double lng_a, double lat_b, double lng_b) {
        double radLat1 = (lat_a * Math.PI / 180.0);
        double radLat2 = (lat_b * Math.PI / 180.0);
        double a = radLat1 - radLat2;
        double b = (lng_a - lng_b) * Math.PI / 180.0;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     * 获取ram文件
     *
     * @param id
     * @return
     * @throws IOException
     */
    public static String getFromRaw(Context context, int id) throws IOException {
        InputStreamReader inputReader = new InputStreamReader(context.getResources().openRawResource(id), "UTF-8");
        BufferedReader bufReader = new BufferedReader(inputReader);
        String line = "";
        String Result = "";
        while ((line = bufReader.readLine()) != null)
            Result += line;
        return Result;
    }

    public static String getTimeStr(Context context, long days, long hours, long minutes) {
        StringBuilder stringBuilder = new StringBuilder();
        if (days != 0) {
            stringBuilder.append(Long.toString(days) + context.getString(R.string.str_dynamics_day));
        } else {
            if (hours != 0) {
                stringBuilder.append(Long.toString(hours) + context.getString(R.string.str_dynamics_hour));
            } else {
                if (minutes != 0) {
                    stringBuilder.append(Long.toString(minutes) + context.getString(R.string.str_dynamics_minute));
                } else {
                    stringBuilder.append(context.getString(R.string.str_dynamics_secound));
                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /*
        移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
        联通：130、131、132、152、155、156、185、186
        电信：133、153、180、189、（1349卫通）
        总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
        */
        String telRegex = "[1][358]\\d{10}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 验证邮箱格式
     */
    public static boolean isEmail(String email) {
        String telRegex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        if (TextUtils.isEmpty(email)) return false;
        else return email.matches(telRegex);
    }

    /**
     * 获取渠道标识
     *
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        Context appContent = context.getApplicationContext();
        String channel = PackerNg.getChannel(context);
        if (StringUtil.isEmpty(channel)) {
            channel = "AVanka";
            ApplicationInfo appInfo = null;
            try {
                appInfo = appContent.getPackageManager().getApplicationInfo(appContent.getPackageName(), PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (appInfo != null) {
                channel = appInfo.metaData.get("UMENG_CHANNEL") + "";
            }
        }
        return channel;
    }

    /**
     * 判断是否是4.4 版本
     *
     * @return
     */
    public static boolean isLowVersion() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT;
    }

    public static void copy(Context context, String text) {
        if (android.os.Build.VERSION.SDK_INT > 11) {
            android.content.ClipboardManager c = (android.content.ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
            c.setPrimaryClip(ClipData.newPlainText("imay_number", text));

        } else {
            android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
            c.setText(text);
        }

    }

    /**
     * 建楼卡入口
     *
     * @return
     */
    public static boolean showRoomHouseUi() {
        long choose_time = PreferenceHelper.getInstance().getLong(PreferenceHelper.ROOMHOUSE_TIME);
        if (choose_time <= 0) {
            return true;

        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            Calendar calendarcur = Calendar.getInstance();
            calendarcur.setTime(new Date(choose_time));
            int yearcur = calendarcur.get(Calendar.YEAR);
            int monthcur = calendarcur.get(Calendar.MONTH) + 1;
            int daycur = calendarcur.get(Calendar.DAY_OF_MONTH);
            if (year == yearcur && month == monthcur && day == daycur) {
                return false;
            } else {
                return true;
            }
        }
    }
}
